<template>
  <div style="background-color: #fffbf8; width: 100%;height: 100%">
    <div :class="[showMask ? 'blur' : '']" id="page" style="background-color: #fffbf8;">

      <van-tabs swipeable @change="onClick">
        <van-tab title="通知">
          <div v-if="notifyTotal>0" style="padding-bottom: 20px">
            <view class="unread">
              <text>{{ notifyReadTotal }} 条未读</text>
              <view class="unread_img">
                <img @click="yiduNotifyClick" src="/static/images/allread.png">
              </view>
            </view>
            <view @touchstart="gtouchstart(item)" @touchmove="gtouchmove()" @touchend="gtouchend(item)"
                  v-for="(item,index) in notifyList" :key="index">
              <view class="times">{{ item.createTime }}</view>
              <view class="notify-item">
                <view class="avatar" style="position: relative">
                  <i v-if="item.readStatus=='0'"
                     style="font-size: 22px;position: absolute;color: red;right: 0px;top: -6px;"
                     class="icon-dian iconfont"></i>
                  <img src="/static/images/tishi.jpeg">
                </view>
                <view class="notify-content">
                  <view class="source">
                    <text style="width: 100%" class="notify-source">{{ item.messageTitle }}
                    </text>
                    <!--                  <text class="source-time">{{ item.createTime }}</text>-->
                  </view>

                  <text class="notify-title">叮！{{ item.messageContent }}</text>
                </view>
              </view>
              <van-cell title="查看详情" is-link />
            </view>
          </div>
          <div v-else>
            <van-empty
              class="custom-image"
              image="https://img.yzcdn.cn/vant/custom-empty-image.png"
              description="空空如也"
            />
          </div>
        </van-tab>
        <van-tab title="评论">
          <div v-if="commentTotal>0" style="padding-bottom: 20px">
            <view class="unread">
              <text>{{ commentReadTotal }} 条未读</text>
              <view class="unread_img">
                <img @click="yiduCommentClick" src="/static/images/allread.png">
              </view>
            </view>
            <view
              @touchstart="gtouchstart(item)" @touchmove="gtouchmove()" @touchend="gtouchend2(item)"
              v-for="(item,index) in commentList" :key="index">
              <view class="times">{{ item.createTime }}</view>
              <view class="notify-item">
                <view class="avatar" style="position: relative">
                  <i v-if="item.readStatus=='0'"
                     style="font-size: 22px;position: absolute;color: red;right: 0px;top: -6px;"
                     class="icon-dian iconfont"></i>
                  <img :src="item.payload.avatar">
                </view>
                <view class="notify-content">
                  <view class="source">
                    <text style="width: 100%" class="notify-source">{{ item.fromName }} {{ item.messageContent }}</text>
                    <!--                <text class="source-time">{{ item.createTime }}</text>-->
                  </view>
                  <text class="notify-title">{{ item.payload.remark }}</text>
                </view>
              </view>
            </view>
          </div>
          <div v-else>
            <van-empty
              class="custom-image"
              image="https://img.yzcdn.cn/vant/custom-empty-image.png"
              description="空空如也"
            />
          </div>
        </van-tab>
      </van-tabs>

      <van-action-sheet
        :show="show"
        :actions="actions"
        @close="onClose"
        @select="onSelect"
        cancel-text="取消"
        close-on-click-action
        @cancel="onCancel"
      />

      <van-action-sheet @cancel="onCancel" cancel-text="取消" @close="onClose" :show="show2" title="通知反馈">
        <div class="content">
          <div class="base-info-content-show" v-if="messageById.payload">
            <ul>
              <li>
                <div class="content-show-l">主题</div>
                <div class="content-show-r">{{ messageById.messageTitle }}</div>
              </li>
              <li>
                <div class="content-show-l">结果</div>
                <div class="content-show-r">{{ messageById.messageContentNew }}</div>
              </li>
              <li>
                <div class="content-show-l">回复</div>
                <div class="content-show-r">{{ messageById.payload.remark }}</div>
              </li>
            </ul>
          </div>

        </div>
      </van-action-sheet>
    </div>
    <mask-layer v-if="showMask" :color="maskColor">
      <view slot="cover" class="cover animated zoomIn faster" style="padding-top: 70%;">
        <button
          class="login-btn bg-primary"
          @click="onLogin"
        >
          去登录
        </button>
      </view>
    </mask-layer>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import {listMessage, listMessageBD, delMessage, delMessageReadStatus1} from '@/api/message'
import {getToken,setToken,removeToken,clearToken} from "../../utils/auth";
import Bus from "../../utils/bus";
import {getUserProfile} from "../../api/user";
export default {
  name: "index",
  data() {
    return {
      showMask:false,
      maskColor:null,
      show: false,
      show2: false,
      actions: [
        {
          name: '删除',
        },
      ],
      notifyList: [],
      commentList: [],
      queryParams: {
        // pageNum: 1,
        // pageSize: 20,
        status: '0',
        type: '1'
      },
      notifyTotal: 0,
      commentTotal: 0,
      notifyReadTotal: 0,
      commentReadTotal: 0,
      open: false,
      messageById: '',
      timeOutEvent: 0,//定时器
    }
  },
  computed: {
    ...mapGetters(['user']),
    token(){
      return getToken();
    }
  },
  mounted() {
    Bus.$on('跳转刷新',(res=>{
      this.getMessageInfo(res);
    }))
    Bus.$on('消息',(res=>{
      this.getMessageInfo();
    }))
    this.getMessageInfo()
  },
  created() {
    // this.getMessageInfo()
  },
  methods: {
    //登录
    onLogin() {
      wx.navigateTo({
        url: '/pages/subpage/login/main'
      });
      setTimeout(() => {
        this.canClick=true
      }, 800);
    },
    onClick(e) {
      if (e.mp.detail.index === 0) {
        this.getMessageInfo2()
      } else {
        this.getMessageInfoComment()
      }
    },
    onCancel() {
      this.show = false
      this.show2 = false
    },
    onClose() {
      this.show = false
      this.show2 = false
    },

    onSelect(event) {
      if (event.mp.detail.name == '删除') {
        delMessage(this.messageById.messageId).then(res => {
          if (res.code === 200) {
            this.getMessageInfo2()
            this.getMessageInfoComment()
            this.setToast({title: '删除消息成功'});
          } else {
            console.log('删除消息失败:', res.msg)
            this.setToast({title: '删除消息失败'});
          }
        })
      }
    },

    gtouchstart(val) {
      this.timeOutEvent = setTimeout(() => {
        this.timeOutEvent = 0;
        //真正长按后应该执行的内容
        this.messageById = val
        this.show = true
        console.log("长按事件触发发", val);
      }, 500);//这里设置定时器，定义长按500毫秒触发长按事件，时间可以自己改，个人感觉500毫秒非常合适
      return false;
    },
    //如果手指有移动，则取消所有事件，此时说明用户只是要移动而不是长按
    gtouchmove() {
      clearTimeout(this.timeOutEvent);//清除定时器
      this.timeOutEvent = 0;
      console.log("取消了");
    },
    //手释放，如果在500毫秒内就释放，则取消长按事件，此时可以执行onclick应该执行的事件
    gtouchend(val) {
      clearTimeout(this.timeOutEvent);//清除定时器
      if (this.timeOutEvent !== 0) {
        //这里写要执行的内容（尤如onclick事件）
        console.log("你这是点击，不是长按");
        this.messageById = val
        this.show2 = true
        delMessageReadStatus1(val.messageId);

        this.getMessageInfo2()
      }
      return false;
    },
    gtouchend2(val) {
      clearTimeout(this.timeOutEvent);//清除定时器
      if (this.timeOutEvent !== 0) {
        //这里写要执行的内容（尤如onclick事件）
        delMessageReadStatus1(val.messageId);
        this.getMessageInfoComment()
        console.log("Ssss",val)
        wx.navigateTo({
          url: '/pages/circle/reply/main?trendsId='+val.payload.trendsId
        });
      }
      return false;
    },
    //获取通知
    getMessageInfo(val) {
      let tokenValue= this.token || val
      if (!tokenValue){
        this.showMask=true
        this.maskColor="rgba(255, 255, 255, .2)"
      }else {
        this.$store.dispatch('GetInfo').then(res => {
          this.showMask=false
          this.maskColor=null
          this.queryParams.toId = this.user.userId
          listMessageBD(this.queryParams).then(response => {
            this.notifyList = response.rows.filter(item => {
              return item.messageTitle != '帖子审核'
            })
            // this.notifyTotal = response.total
            this.notifyTotal = this.notifyList.length
            this.notifyList.map(item => {
              item.payload = JSON.parse(item.payload)
              item.messageContentNew=item.messageContent.substring(0,item.messageContent.length-7)
            })
            let list = JSON.parse(JSON.stringify(this.notifyList)).filter(item => {
              return item.readStatus == '0'
            })
            this.notifyReadTotal = list.length
          })
        }).catch(err => {
          console.log(err)
          this.$store.dispatch('LogOut').then(() => {
            this.setToast({ title: err })
            wx.navigateTo({
              url: '/pages/subpage/login/main'
            })
          })
        })
      }
    },
    getMessageInfo2(){
      this.queryParams.toId = this.user.userId
      listMessageBD(this.queryParams).then(response => {
        this.notifyList = response.rows.filter(item => {
          return item.messageTitle != '帖子审核'
        })
        // this.notifyTotal = response.total
        this.notifyTotal = this.notifyList.length
        this.notifyList.map(item => {
          item.payload = JSON.parse(item.payload)
          item.messageContentNew=item.messageContent.substring(0,item.messageContent.length-7)
        })
        let list = JSON.parse(JSON.stringify(this.notifyList)).filter(item => {
          return item.readStatus == '0'
        })
        this.notifyReadTotal = list.length
      })
    },

    getMessageInfoComment() {
      this.queryParams.toId = this.user.userId
      listMessage(this.queryParams).then(response => {
        this.commentList = response.rows.filter(item => {
          return item.messageTitle == '动态'
        })
        this.commentTotal = this.commentList.length
        this.commentList.map(item => {
          item.payload = JSON.parse(item.payload)
          item.payload.avatar = this.changeAvatar(item.payload.avatar)
        })
        let list = JSON.parse(JSON.stringify(this.commentList)).filter(item => {
          return item.readStatus == '0'
        })
        this.commentReadTotal = list.length
        // this.commentTotal = response.total
      })
    },
    yiduNotifyClick() {
      let ids = this.notifyList.map(item => item.messageId)
      wx.showModal({
        title: '提示',
        content: "是否全部设置为已读！",
        success(res) {
          if (res.confirm) {
            // console.log("sssssssss")
            delMessageReadStatus1(ids);
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },
    yiduCommentClick() {
      let ids = this.commentList.map(item => item.messageId)
      wx.showModal({
        title: '提示',
        content: "是否全部设置为已读！",
        success(res) {
          if (res.confirm) {
            // console.log("sssssssss")
            delMessageReadStatus1(ids);
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  }
}
</script>

<style>
.van-ellipsis {
  font-size: 16px;
}
.van-cell__title{
  margin-left: 8px;
}
</style>
<style scoped>
cover {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.login-btn {
  width: 50%;
  text-align: center;
  font-size: 32rpx;
  border-radius: 15rpx;
}

.base-info-head {
  text-align: left;
  height: 40px;
  line-height: 35px;
  font-size: 18px;
  font-weight: 600;
  color: #2E2E2E;
  padding-left: 10px;
  border-bottom: 1px solid #F0F0F2;
}

.base-info-content-show {
  cursor: pointer;
  /*padding: 16px 112px 16px 0;*/
  padding: 10px 25px;
  position: relative;
  background: #F8F8F8;
}

.base-info-content-show ul li {
  line-height: 24px;
  font-size: 14px;
  margin-bottom: 20px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

.base-info-content-show ul li .content-show-l {
  width: 30px;
  color: #555666;
  margin-right: 40px;
  font-weight: 600;
  -ms-flex-negative: 0;
  flex-shrink: 0;
  /*padding-left: 16px;*/
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-sizing: content-box;
  box-sizing: content-box;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

.base-info-content-show ul li .content-show-r {
  color: #222226;
  word-break: break-all;
}

.unread {
  display: flex;
  width: 100%;
  background: #F0F4F3;
  color: #9A9C9B;
  height: 25px;
  padding: 5px 0;
  text-align: left;
}

.unread text {
  margin-left: 5%;
  width: 20%;
  display: inline-block;
  line-height: 25px;
  font-size: 11px;
}

.unread_img {
  margin-right: 5%;
  width: 70%;
  text-align: right;
}

.unread img {
  display: inline-block;
  width: 20px;
  height: 20px;
  vertical-align: middle;
}

.times {
  border-radius: 6px;
  text-align: center;
  color: #fff;
  font-size: 12px;
  width: 35%;
  background: #BEBEBE;
  margin: 10px auto;
  border: 1px solid #BEBEBE;
  height: 20px;
  line-height: 20px;
}

.notify-item {
  box-shadow: 0 4px 10px rgba(58, 58, 58, 0.1);
  display: flex;
  padding: 10px 5%;
  margin: 0 auto;
  background: #ffffff;
  /*border-bottom: solid 1px #ebebeb;*/
}

.notify-item img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin: 3px 0;
}

.notify-item .avatar {
  width: 15%;
}

.notify-item .notify-content {
  width: 85%;
  text-align: left;
}

.notify-item .notify-content text {
  -webkit-line-clamp: 1;
  overflow: hidden;
  word-break: break-all;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}

.source {
  width: 100%;
  display: flex;
}

.source-time {
  line-height: 21px;
  margin: 0 0 8px 0;
  text-align: right;
  color: #818A8F;
  font-size: 12px;
  width: 50%;
}

.notify-item .notify-content .notify-source {
  /*color: #818A8F;*/
  width: 50%;
  font-size: 15px;
  margin: 0 0 8px 0;
}

.notify-item .notify-content .notify-title {
  color: #AFAFAF;
  font-size: 14px;
  line-height: 17px;
}

.placehold {
  padding: 40px 0;
  font-size: 14px
}


.van-tabs__wrap {
  border-top: 1px solid #F4F4F4;
}
</style>
